package com.example.gulimall.order.controller.web;

import com.example.common.utils.R;
import com.example.gulimall.order.entity.OrderEntity;
import com.example.gulimall.order.service.OrderService;
import com.example.gulimall.order.vo.OrderConfirmVo;
import com.example.gulimall.order.vo.OrderSubmitVo;
import com.example.gulimall.order.vo.SubmitResponseVo;
import exception.NoStockException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class OrderWebController {
    @Autowired
    OrderService orderService;
    @ResponseBody
    @GetMapping("/order/status/{orderSn}")
    public R getOrderStatus(@PathVariable("orderSn") String orderSn){
       OrderEntity orderEntity= orderService.getOrderByOrderSn(orderSn);
       return R.ok().setData(orderEntity);
    }
    @GetMapping("/toTrade")
    public String toTrade(Model model){
        OrderConfirmVo confirmVo= orderService.confirmOrder();

        model.addAttribute("orderConfirmData",confirmVo);
        return "confirm";
    }
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo orderSubmitVo, Model model, RedirectAttributes redirectAttributes){
        //取创建订单，
        // 验令牌，
        // 验价格，
        // 锁库存。。。。最
        // 终下单成功来到支付选择页，
        // 下单失败回到订单确认页重新确认订单信息
        try {
            SubmitResponseVo responseVo=orderService.submitOrder(orderSubmitVo);
            System.out.println("订单提交的数据"+orderSubmitVo);
            if (responseVo.getCode()==0){
                //下单成功来到支付选择页
                model.addAttribute("submitOrderResp",responseVo);
                return "pay";
            }else {
                String msg="下单失败";
                switch (responseVo.getCode()){
                    case 1:msg+="订单信息过期，请刷新再次提交哦"; break;
                    case 2:msg+="订单商品价格发生变化，请确认后在提交";break;
                    case 3:msg+="库存锁定失败，商品库存不足";break;
                }
                redirectAttributes.addFlashAttribute("msg",msg);
                return "redirect:http://order.mall.com/toTrade";
            }
        }catch (NoStockException e){
            redirectAttributes.addFlashAttribute("msg",e.getMessage());
            return "redirect:http://order.mall.com/toTrade";
        }

    }
}
